import { defineStore } from 'pinia';
import { createStorage } from '@/utils/Storage';
import { store } from '@/store';
import { ACCESS_TOKEN, CURRENT_USER, IS_LOCKSCREEN, userId, custNo, operatorList, changeInitPassword, refreshTokena, loginName } from '@/store/mutation-types';
import { ResultEnum } from '@/enums/httpEnum';

const Storage = createStorage({ storage: localStorage });
import { getUserInfo, login } from '@/api/system/user';
import { storage } from '@/utils/Storage';
import { useMessage } from 'naive-ui';

const message = useMessage();
export interface IUserState {
  token: string;
  username: string;
  welcome: string;
  avatar: string;
  permissions: any[];
  info: any;
}

export const useUserStore = defineStore({
  id: 'app-user',
  state: (): IUserState => ({
    token: Storage.get(ACCESS_TOKEN, ''),
    username: '',
    welcome: '',
    avatar: '',
    permissions: [],
    info: Storage.get(CURRENT_USER, {}),
  }),
  getters: {
    // token
    getToken(): string {
      return this.token;
    },
    // 头像
    getAvatar(): string {
      return this.avatar;
    },
    // 名字
    getNickname(): string {
      return this.username;
    },
    // 权限
    getPermissions(): [any][] {
      return this.permissions;
    },
    // 用户信息
    getUserInfo(): object {
      return this.info;
    },
  },
  actions: {
    setToken(token: string) {
      this.token = token;
    },
    setAvatar(avatar: string) {
      this.avatar = avatar;
    },
    setPermissions(permissions) {
      this.permissions = permissions;
    },
    setUserInfo(info) {
      this.info = info;
    },
    // 登录
    async login(userInfo) {
      try {
        const response = await login(userInfo);
        console.log(response);
        const { data } = response;
        if (response.data.sysHead.retCd === "000000") {
          
          storage.set(loginName, response.data.body.loginName) //token
          storage.set(refreshTokena, response.data.localHead.refreshToken) //token
          storage.set(ACCESS_TOKEN, response.data.localHead.token) //token
          storage.set(changeInitPassword, response.data.body.changeInitPassword) // 是否需要修改密码
          storage.set(userId, JSON.stringify(response.data.body.userId)); // userID
          storage.set(custNo, response.data.body.custNo); // 客户号
          storage.set(IS_LOCKSCREEN, false); // 屏锁
          this.setToken(response.data.localHead.token);
        }
        return Promise.resolve(response);
      } catch (e) {
        return Promise.reject(e);
      }
    },
    // login
    // 获取用户信息
    GetInfo() {
      const that = this;
      return new Promise((resolve, reject) => {
        let userId = storage.get('userId')
        getUserInfo({ userId })
          .then((res) => {
            console.log(res);

            const result = res;
            if (result.data.sysHead.retCd === "000000" && result.status == 200) {
              console.log(result);

              const permissionsList = result.data.body.children;
              that.setPermissions(permissionsList);
              storage.set(operatorList, JSON.stringify(result.data.body.operatorList));
              that.setUserInfo(result);
            } else {
              reject(new Error('getInfo: permissionsList must be a non-null array !'));
            }
            that.setAvatar(result.avatar);
            resolve(res);
          })
          .catch((error) => {
            reject(error);
          });
      });
    },


    // 登出
    async logout() {
      this.setPermissions([]);
      this.setUserInfo('');
      storage.remove(ACCESS_TOKEN);
      storage.remove(CURRENT_USER);
      storage.remove(userId);
      storage.remove(refreshTokena);
      storage.remove(loginName);
      storage.remove(changeInitPassword);
      storage.remove(operatorList);
      storage.remove(custNo);
      return Promise.resolve('');
    },
  },
});

// Need to be used outside the setup
export function useUserStoreWidthOut() {
  return useUserStore(store);
}
